<template>
  <div class="login-content">
    <h1>智慧社区服务平台</h1>
    <div class="login-wrap">
      <div class="ms-login">
        <div class="ms-title">登陆</div>
        <el-form :model="param" :rules="rules" ref="login" label-width="0px" class="ms-content">
          <el-form-item prop="phone">
            <el-input v-model="param.phone" placeholder="请输入手机号" size="normal">
              <el-button slot="prepend" icon="el-icon-phone"></el-button>
            </el-input>
          </el-form-item>
          <!-- <el-form-item prop="password">
            <el-input type="password" placeholder="密码" v-model="param.password"
              @keyup.enter.native="submitForm()">
              <el-button slot="prepend" icon="el-icon-lx-lock"></el-button>
            </el-input>
          </el-form-item> -->
          <el-form-item label="" prop="code">
            <div class="verify-wrapper">
              <el-input type="text" maxlength="6" placeholder="验证码" size="normal" class="input-c"
                        v-model="param.code">
                <el-button slot="prepend" icon="el-icon-lock"></el-button>
                <el-button slot="append" :disabled="disabled" @click="getCode">{{valiBtn}}</el-button>
              </el-input>
            </div>
          </el-form-item>
          <div class="login-btn">
            <el-button type="primary" @click="submitForm()">登陆</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {
  loginPost,
  mlogin,
  sendMsg
} from '../../api/login';
import {
  getPermission
} from '../../api/user';
var loginRequest = {
  url: '/usercenter/login'
};
var sendMsgRequest = {
  url: '/usercenter/sendmsg/{id}'
};
var phoneLogin = {
  url: '/usercenter/loginMsg'
};
var perRequest = {
  url: '/usercenter/user-permission/current-user-permission'
};
let Base64 = require('js-base64').Base64;

export default {

  data: function () {
    var checkPhone = (rule, value, callback) => {
      const reg = /^0?(13[0-9]|15[012356789]|18[0-9]|14[578]|16[6]|17[035768]|19[19])[0-9]{8}$/
      if (reg.test(value)) {
        return callback();
      }
      callback('请输入合法的手机号');
    };
    return {
      param: {
        phone: '',
        code: ''
      },
      rules: {
        phone: [{
          validator: checkPhone,
          required: true,
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '请输入验证码',
          trigger: 'blur'
        }]
      },
      dialogVisible: false, // 对话框显示和隐藏
      valiBtn: '获取验证码',
      disabled: false,
      // rules: {
      // 	username: [{
      // 		required: true,
      // 		message: '请输入用户名',
      // 		trigger: 'blur'
      // 	}],
      // 	password: [{
      // 		required: true,
      // 		message: '请输入密码',
      // 		trigger: 'blur'
      // 	}]
      // },
      permission: {}
    };
  },
  created(){
    let openkey = localStorage.getItem('openKey')
    if(openkey){
      mlogin({openKey: openkey})
          .then((res) => {
            console.log(res, 'loginnnnnn')
            switch (res.code) {
              case 0:
                //登录成功，写入token
                this.$message.success('登录成功');
                let phone = this.param.phone ? this.param.phone : '社智在线用户'
                localStorage.setItem('ms_username', phone);
                localStorage.setItem('token', res.data.token);
                let level = res.data.superManager == 1 ? process.env.superManager : res.data.level
                localStorage.setItem('level', level);
                localStorage.setItem('superManager', res.data.superManager);
                localStorage.setItem('userid', res.data.uid);
                localStorage.setItem('is_szzx',0);
                localStorage.setItem('nickName', res.data.nickName);
                getPermission(perRequest).then((res2) => {
                  localStorage.setItem('userPermissions', JSON.stringify(res2
                      .data));
                  this.setUserPermission(res2.data);
                  this.$router.push('/home');
                });
                localStorage.removeItem('openKey')
                //this.$router.push('/');
                break;
              case 200003:
                //用户名密码错误
                this.$message.error(res.message);
                break;
              case 200002:
                //用户名密码错误
                this.$message.error(res.message);
                break;
              case 200011:
                this.$message.error(res.message);
                break;
              case 200012:
                this.$message.error(res.message);
                break;
              case 200004:
                //用户被禁用
                this.$message.error(res.message);

                break;
              default:
                //系统维护中，跳页面吧
                this.$message.warning('系统维护中....');
            }
          })
          .catch((error) => {
            localStorage.removeItem('openKey')
            this.$message.error(error.message);
            return Promise.reject();
          });
    }
  },
  methods: {
    getCode() {
      this.$refs['login'].validateField('phone', (err) => {
        if (err) {
          console.log('未通过')
          return;
        } else {
          console.log('已通过')
          this.tackBtn(); //验证码倒数60秒
          let fd = new FormData(); //POST 请求需要 转化为Form
          fd.append('PhoneNumber', this.param.phone);
          fd.append('NeedCheck', 2);
          console.log(this.param.phone)
          sendMsgRequest.id = this.param.phone
          console.log(sendMsgRequest)
          sendMsg(sendMsgRequest)
              .then((res) => {
                console.log(res)
              })
        }
      })
    },
    tackBtn() { //验证码倒数60秒
      let time = 60;
      let timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.valiBtn = '获取验证码';
          this.disabled = false;
        } else {
          this.disabled = true;
          this.valiBtn = time + '秒后重试';
          time--;
        }
      }, 1000);
    },
    setUserPermission(userPermissionList) {
      this.doSetUserPermission(userPermissionList);
      sessionStorage.setItem('permission', JSON.stringify(this.permission));
      //sessionStorage.permission = JSON.stringify(this.permission);
    },
    doSetUserPermission(userPermissionList) {
      //逐级遍历
      for (var i = 0; i < userPermissionList.length; i++) {
        //若不是顶级，将冒号转化为层级关系
        this.toLevelShow(userPermissionList[i].permissionCode);
        //如果还有子集，进行递归设置
        if (userPermissionList[i].children.length > 0) {
          this.doSetUserPermission(userPermissionList[i].children);
        }
      }
    },
    toLevelShow(code) {
      var codeArr = code.split(':');
      if (codeArr.length == 1) {
        this.permission[codeArr[0]] = true;
      } else if (codeArr.length == 2) {
        if (typeof this.permission[codeArr[0]] == 'undefined' || this.permission[codeArr[0]] == true) {
          this.permission[codeArr[0]] = {};
        }
        this.permission[codeArr[0]][codeArr[1]] = true;
      } else if (codeArr.length == 3) {
        if (typeof this.permission[codeArr[0]] == 'undefined' || this.permission[codeArr[0]] == true) {
          this.permission[codeArr[0]] = {};
        }
        if (typeof this.permission[codeArr[0]][codeArr[1]] == 'undefined' || this.permission[codeArr[0]][
            codeArr[1]
            ] == true) {
          this.permission[codeArr[0]][codeArr[1]] = {};
        }
        this.permission[codeArr[0]][codeArr[1]][codeArr[2]] = true;
      }
    },
    submitForm() {
      this.$refs.login.validate((valid) => {
        if (valid) {
          //对密码进行base64加密
          // this.param.password = Base64.encode('ct'+this.param.password);
          let parameter = {
            phone: this.param.phone,
            msgCode: this.param.code
          };
          phoneLogin.data = parameter;
          loginPost(phoneLogin)
              .then((res) => {
                console.log(res, 'loginnnnnn')
                switch (res.code) {
                  case 0:
                    //登录成功，写入token
                    this.$message.success('登录成功');
                    localStorage.setItem('ms_username', this.param.phone);
                    localStorage.setItem('token', res.data.token);
                    let level = res.data.superManager == 1 ? process.env.superManager : res.data.level
                    localStorage.setItem('level', level);
                    localStorage.setItem('superManager', res.data.superManager);
                    localStorage.setItem('userid', res.data.uid);
                    localStorage.setItem('is_szzx',0);
                    localStorage.setItem('nickName', res.data.nickName);
                    getPermission(perRequest).then((res2) => {
                      localStorage.setItem('userPermissions', JSON.stringify(res2
                          .data));
                      this.setUserPermission(res2.data);
                      this.$router.push('/home');
                    });
                    //this.$router.push('/');
                    break;
                  case 200003:
                    //用户名密码错误
                    this.$message.error(res.message);
                    break;
                  case 200002:
                    //用户名密码错误
                    this.$message.error(res.message);
                    break;
                  case 200011:
                    this.$message.error(res.message);
                    break;
                  case 200012:
                    this.$message.error(res.message);
                    break;
                  case 200004:
                    //用户被禁用
                    this.$message.error(res.message);
                    break;
                  default:
                    //系统维护中，跳页面吧
                    this.$message.warning('系统维护中....');
                }
              })
              .catch((error) => {
                this.$message.error(error.message);
                return Promise.reject();
              });
        } else {
          this.$message.error('请输入账号和密码');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.login-content {
  position: relative;
  width: 100%;
  height: 100%;

}

.login-content h1 {
  font-size: 28px;
  height: 65px;
  line-height: 65px;
  padding-left: 60px;
  color: #4940FD;
  font-weight: 400;
}

.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url(../../assets/img/login-bg.png);
  background-size: 100%;
}

.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: left;
  font-size: 20px;
  color: #4940FD;
  font-weight: bold;
  border-bottom: 1px solid #ddd;
  padding-left: 40px;
}

.ms-login {
  position: absolute;
  left: 80%;
  top: 50%;
  width: 300px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: #FFFFFF;
  overflow: hidden;
}

.ms-content {
  padding: 30px 30px;
}

.login-btn {
  text-align: center;
}

.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}

.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}
.input-c{
  margin: 10px 0;
}
</style>